const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { foodService, searchHistoryService } = require('../services');
const logger = require('../utils/logger');

/**
 * 获取全部食物列表
 */
const getAllFoods = catchAsync(async (req, res) => {
  try {
    // 只提供排序选项
    const options = {
      sortBy: req.query.sortBy || 'name',
      sortOrder: req.query.sortOrder || 'asc',
    };
    
    // 调用服务获取全部食物
    const result = await foodService.getAllFoods(options);
    
    res.send({
      error: 0,
      body: result,
      message: ''
    });
  } catch (err) {
    console.error('获取全部食物列表失败:', err);
    res.status(err.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: err.message || '获取全部食物列表失败'
    });
  }
});

/**
 * 搜索和筛选食物
 */
const searchFoods = catchAsync(async (req, res) => {
  try {
    // 构建筛选条件
    const filter = {};
    
    // 名称搜索
    if (req.query.name) {
      filter.name = { $regex: req.query.name, $options: 'i' }; // 不区分大小写
    }
    
    // 按分类筛选
    if (req.query.categoryId) {
      filter.categoryId = req.query.categoryId;
    }
    
    // 按验证状态筛选
    if (req.query.isVerified !== undefined) {
      filter.isVerified = req.query.isVerified;
    }
    
    // 按营养素筛选
    if (req.query.nutrient) {
      const nutrient = req.query.nutrient;
      
      // 特殊处理calories字段，它位于顶层而不是nutrition中
      if (nutrient === 'calories') {
        if (req.query.nutrientMin !== undefined) {
          filter.calories = { $gte: Number(req.query.nutrientMin) };
        }
        if (req.query.nutrientMax !== undefined) {
          filter.calories = { ...(filter.calories || {}), $lte: Number(req.query.nutrientMax) };
        }
      } 
      // 处理其他营养素字段，它们在nutrition对象中
      else {
        if (req.query.nutrientMin !== undefined) {
          filter[`nutrition.${nutrient}`] = { $gte: Number(req.query.nutrientMin) };
        }
        if (req.query.nutrientMax !== undefined) {
          filter[`nutrition.${nutrient}`] = { ...(filter[`nutrition.${nutrient}`] || {}), $lte: Number(req.query.nutrientMax) };
        }
      }
    }
    
    // 查询选项
    const options = {
      sortBy: req.query.sortBy || 'name',
      sortOrder: req.query.sortOrder || 'asc',
      page: req.query.page ? parseInt(req.query.page, 10) : 1,
      limit: req.query.limit ? parseInt(req.query.limit, 10) : 20,
    };
    
    // 调用服务搜索食物
    const result = await foodService.searchFoods(filter, options);
    
    // 保存搜索历史（如果有用户登录且有搜索关键词）
    if (req.user && req.query.name && req.query.name.trim() !== '') {
      try {
        // 记录原始用户对象结构，便于调试
        logger.info(`搜索历史保存: 原始用户对象信息: ${JSON.stringify({
          hasUser: !!req.user,
          userId: req.user._id || req.user.id,
          userIdType: typeof (req.user._id || req.user.id),
          userProps: Object.keys(req.user)
        })}`);
        
        // 确定用户ID - 支持多种格式
        let userId = req.user._id || req.user.id;
        
        // 确保有用户ID
        if (!userId) {
          logger.warn('无法保存搜索历史: 无法确定用户ID', { 
            user: JSON.stringify({
              hasUser: !!req.user,
              userProps: req.user ? Object.keys(req.user) : []
            })
          });
        } else {
          // 创建搜索历史
          logger.info(`准备保存搜索历史记录: userId=${userId}, keyword=${req.query.name}`);
          
          const savedHistory = await searchHistoryService.createSearchHistory({
            userId: userId,
            keyword: req.query.name,
            type: 'food'
          });
          
          // 检查结果是否包含错误
          if (savedHistory && savedHistory.error) {
            logger.warn(`搜索历史保存失败: ${savedHistory.message}`);
          } else {
          logger.info(`搜索历史保存成功: ${savedHistory._id}`);
          }
        }
      } catch (historyError) {
        // 记录详细错误信息
        logger.error(`保存搜索历史失败: ${historyError.message}`);
        logger.error(`错误类型: ${historyError.name}`);
        logger.error(`错误详情: ${JSON.stringify(historyError)}`);
        if (historyError.stack) {
          logger.error(`错误堆栈: ${historyError.stack}`);
        }
      }
    } else {
      // 记录未尝试保存的原因
      logger.info(`未尝试保存搜索历史: user存在=${!!req.user}, 关键词存在=${!!req.query.name}`);
    }
    
    res.send({
      error: 0,
      body: result,
      message: ''
    });
  } catch (err) {
    console.error('搜索食物失败:', err);
    res.status(err.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: err.message || '搜索食物失败'
    });
  }
});

/**
 * 获取食物详情
 */
const getFoodById = catchAsync(async (req, res) => {
  const food = await foodService.getFoodById(req.params.foodId);
  
  res.send({
    error: 0,
    body: food,
    message: ''
  });
});

/**
 * 更新食物分类
 * 用于管理员重新分类食物
 */
const updateFoodCategory = catchAsync(async (req, res) => {
  try {
    const { foodId, categoryName } = req.body;
    
    if (!foodId || !categoryName) {
      throw new ApiError(httpStatus.BAD_REQUEST, '食物ID和分类名称不能为空');
    }
    
    console.log(`更新食物分类，食物ID: ${foodId}, 新分类: ${categoryName}`);
    
    // 先获取或创建分类
    const category = await foodService.getOrCreateFoodCategory(categoryName);
    
    // 找到食物
    const food = await foodService.getFoodById(foodId);
    
    if (!food) {
      throw new ApiError(httpStatus.NOT_FOUND, '食物不存在');
    }
    
    // 使用Mongoose的原始操作更新食物分类
    const updatedFood = await require('../models/food.model')
      .findByIdAndUpdate(
        foodId, 
        { categoryId: category._id },
        { new: true }
      );
    
    console.log(`成功更新食物 "${food.name}" 的分类为 "${category.name}"`);
    
    res.send({
      error: 0,
      body: {
        _id: updatedFood._id,
        name: updatedFood.name,
        category: {
          _id: category._id,
          name: category.name
        }
      },
      message: '更新分类成功'
    });
  } catch (err) {
    console.error('更新食物分类失败:', err);
    res.status(err.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: err.message || '更新食物分类失败'
    });
  }
});

/**
 * 创建新的食物
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Promise<void>}
 */
const createFood = async (req, res) => {
  try {
    logger.info('收到创建食物请求');
    
    const food = await foodService.createFood(req.body);
    
    res.status(201).json({
      error: 0,
      body: food,
      message: '食物添加成功'
    });
    
    logger.info(`食物创建成功: ${food.name}, ID: ${food._id}`);
  } catch (error) {
    logger.error(`创建食物失败: ${error.message}`);
    
    res.status(400).json({
      error: 1, 
      body: null,
      message: error.message || '添加食物失败'
    });
  }
};

/**
 * 获取所有食物分类
 */
const getAllFoodCategories = catchAsync(async (req, res) => {
  try {
    logger.info('获取所有食物分类');
    
    // 是否只获取活跃分类的参数
    const options = {
      activeOnly: req.query.activeOnly === 'true'
    };
    
    const categories = await foodService.getAllFoodCategories(options);
    
    res.status(httpStatus.OK).send({
      error: 0,
      body: {
        categories
      },
      message: ''
    });
  } catch (error) {
    logger.error('获取食物分类失败:', error);
    res.status(error.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: error.message || '获取食物分类失败'
    });
  }
});

/**
 * 更新食物分类
 */
const editFoodCategory = catchAsync(async (req, res) => {
  try {
    const { categoryId } = req.params;
    
    if (!categoryId) {
      throw new ApiError(httpStatus.BAD_REQUEST, '缺少分类ID');
    }
    
    logger.info(`更新食物分类请求: ${categoryId}`);
    const updateData = {
      name: req.body.name,
      description: req.body.description,
      icon: req.body.icon, // 注意API使用icon，而数据库字段是image
      order: req.body.order,
      isActive: req.body.isActive
    };
    
    const updatedCategory = await foodService.updateFoodCategory(categoryId, updateData);
    
    res.status(httpStatus.OK).send({
      error: 0,
      body: updatedCategory,
      message: '分类更新成功'
    });
  } catch (error) {
    logger.error('更新食物分类失败:', error);
    res.status(error.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: error.message || '更新食物分类失败'
    });
  }
});

/**
 * 删除食物分类
 */
const deleteFoodCategory = catchAsync(async (req, res) => {
  try {
    const { categoryId } = req.params;
    
    if (!categoryId) {
      throw new ApiError(httpStatus.BAD_REQUEST, '缺少分类ID');
    }
    
    logger.info(`删除食物分类请求: ${categoryId}`);
    
    const result = await foodService.deleteFoodCategory(categoryId);
    
    res.status(httpStatus.OK).send({
      error: 0,
      body: result,
      message: '分类删除成功'
    });
  } catch (error) {
    logger.error('删除食物分类失败:', error);
    res.status(error.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: error.message || '删除食物分类失败'
    });
  }
});

/**
 * 创建食物分类
 */
const createFoodCategory = catchAsync(async (req, res) => {
  try {
    logger.info('收到创建食物分类请求');
    
    // 提取请求数据，图标字段适配
    const categoryData = {
      name: req.body.name,
      description: req.body.description || '',
      icon: req.body.icon || '', // API使用icon，但数据库字段是image
      order: req.body.order !== undefined ? req.body.order : 0,
      isActive: req.body.isActive !== undefined ? req.body.isActive : true
    };
    
    // 调用服务创建分类
    const category = await foodService.createFoodCategory(categoryData);
    
    res.status(httpStatus.CREATED).send({
      error: 0,
      body: category,
      message: '分类创建成功'
    });
  } catch (error) {
    logger.error('创建食物分类失败:', error);
    res.status(error.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: error.message || '创建食物分类失败'
    });
  }
});

/**
 * 批量更新食物分类排序
 */
const updateCategoriesOrder = catchAsync(async (req, res) => {
  try {
    const { categories } = req.body;
    
    logger.info(`收到批量更新分类排序请求，共${categories.length}个分类`);
    
    const result = await foodService.updateCategoriesOrder(categories);
    
    res.status(httpStatus.OK).send({
      error: 0,
      body: result,
      message: '分类排序更新成功'
    });
  } catch (error) {
    logger.error('批量更新分类排序失败:', error);
    res.status(error.statusCode || httpStatus.INTERNAL_SERVER_ERROR).send({
      error: 1,
      body: null,
      message: error.message || '批量更新分类排序失败'
    });
  }
});

const getFoodCategories = catchAsync(async (req, res) => {
  // ... existing code ...
});

const deleteFood = catchAsync(async (req, res) => {
  await foodService.deleteFoodById(req.params.foodId);
  res.status(httpStatus.NO_CONTENT).send(); // Or send a success message as per API rule
});

module.exports = {
  getAllFoods,
  searchFoods,
  getFoodById,
  updateFoodCategory,
  createFood,
  getAllFoodCategories,
  editFoodCategory,
  deleteFoodCategory,
  createFoodCategory,
  updateCategoriesOrder,
  getFoodCategories,
  deleteFood,
};